package com.rabbit.diary.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbit.diary.bean.SysBlogType;
import com.rabbit.diary.bean.TblSynBlog;
import com.rabbit.diary.dao.BlogMapper;
import com.rabbit.diary.dao.SysBlogTypeMapper;
import com.rabbit.diary.service.ISysBlogTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 剽悍一小兔
 * @since 2022-04-17
 */
@Service
public class SysBlogTypeServiceImpl extends ServiceImpl<SysBlogTypeMapper, SysBlogType> implements ISysBlogTypeService {

    @Autowired
    SysBlogTypeMapper sysBlogTypeMapper;

    @Autowired
    BlogMapper blogMapper;

    @Override
    public List<SysBlogType> selectAll() {
        // 创建查询条件对象
        QueryWrapper<SysBlogType> queryWrapper = new QueryWrapper<>();
        // 设置查询条件：用户ID等于当前登录用户的ID
        queryWrapper.eq("user_id", StpUtil.getLoginId());
        // 查询符合条件的博客分类列表
        List<SysBlogType> sysBlogTypes = sysBlogTypeMapper.selectList(queryWrapper);
        // 获取所有博客分类的ID
        Set<Integer> blogIds = sysBlogTypes.stream().map(SysBlogType::getId).collect(Collectors.toSet());
        // 根据博客分类ID查询对应的博客列表
        List<TblSynBlog> tblSynBlogs = blogMapper.selectList(new LambdaQueryWrapper<TblSynBlog>()
                .in(TblSynBlog::getBlogType, blogIds));
        // 将博客列表按照分类ID进行分组
        Map<String, List<TblSynBlog>> tblSynBlogsMap = tblSynBlogs.stream().collect(Collectors.groupingBy(TblSynBlog::getBlogType));
        // 遍历博客分类列表，设置每个博客分类对应的博客数量
        sysBlogTypes.forEach(e -> {
            List<TblSynBlog> synBlogs = tblSynBlogsMap.get(e.getId() + "");
            if (synBlogs != null) {
                e.setBlogNumber(synBlogs.size());
            } else {
                e.setBlogNumber(0);
            }
        });
        // 返回博客分类列表
        return sysBlogTypes;
    }

    @Override
    public SysBlogType selectOne(Integer id) {
        QueryWrapper<SysBlogType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        queryWrapper.eq("user_id", StpUtil.getLoginId());
        return sysBlogTypeMapper.selectOne(queryWrapper);
    }

    @Override
    public void delete(Integer id) {
        sysBlogTypeMapper.deleteById(id);
    }

    @Override
    public SysBlogType getByTypeId(String blogType) {
        return baseMapper.selectById(Integer.parseInt(blogType));
    }
}
